package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubjectData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectMapper subjectMapper;

    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext analysisContext) {
        System.out.println(data);

        //处理读取出来的数据
        String levelOneTitle = data.getLevelOneTitle(); //一级分类
        String levelTwoTitle = data.getLevelTwoTitle(); //二级分类

        Subject subjectLevelOne = this.getByTitle(levelOneTitle);
        String parentId = null;
        //根据levelOneTitle判断一级分类是否重复
        if (subjectLevelOne == null){
            //不重复，将一级分类存入数据库中并得到一级类别的Id
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(levelOneTitle); //一级分类名称
            subjectMapper.insert(subject);
            parentId = subject.getId();
        }else {
            //重复则将Id取出，不插入
            parentId = subjectLevelOne.getId();
        }

        //判断二级分类是否重复
        Subject subjectLevelTwo = this.getSubjectTitle(levelTwoTitle,parentId);
        if (subjectLevelTwo == null){
            //不重复，将二级分类存入数据库中
            Subject subject = new Subject();
            subject.setParentId(parentId);
            subject.setTitle(levelTwoTitle);
            subjectMapper.insert(subject);
        }
        //重复则不插入

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("读取完毕！");
    }

    //根据分类名称查询这个一级分类是否存在
    private Subject getByTitle(String title){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",0);
        return subjectMapper.selectOne(queryWrapper);
    }

    //根据分类名称和父id查询这个二级分类是否存在
    private Subject getSubjectTitle(String title, String parentId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",parentId);
        return subjectMapper.selectOne(queryWrapper);
    }

}
